import logging2 as logging
from ssh import Host
import fabric


PROMPT = ['# ', '>>> ', '> ', '$']


class Terminal:
    host: Host
    cnn: fabric.Connection = None
    stdin = None
    stdout = None
    stderr = None

    def __init__(self, host: Host):
        self.host = host

    def __del__(self):
        self.disconnect()

    # 是否已连接
    def is_connected(self):
        if not self.cnn:
            return False

        return True

    # 连接主机
    def connect(self):
        if self.is_connected():
            return

        try:
            self.cnn = fabric.Connection(self.host.name, port=self.host.port, user=self.host.username)
        except Exception as ex:
            logging.error(ex, exc_info=True)

    # 断开连接
    def disconnect(self):
        if not self.is_connected():
            return

        try:
            self.cnn.close()
        finally:
            self.cnn = None

    # 执行单一命令
    def exec(self, cmd: str) -> ():
        if not self.is_connected():
            return

        try:
            result = self.cnn.run(cmd)

        except Exception as ex:
            logging.warning(ex, exc_info=True)

    # 显示结果
    def show_output(self, result):
        print('\033[32m{}:'.format(self.host.name))

        try:
            if len(result.stdout) > 0:
                print(result.stdout)

            # if len(err) > 0:
            #     print('\n\033[31m' + err)
        except Exception as ex:
            logging.warning(ex)

    # 执行带预期结果的命令并执行下一步给定操作
    def exec_with_expect(self, cmd: str, expect_next: list):
        # child = pexpect.spawn(cmd)
        # for item in expect_next:
        #     ret = child.expect([pexpect.TIMEOUT, item.get('expect')])
        #     if ret == 1:
        #         child.sendline(item.next)
        #     elif ret == 0:
        #         print("timeout")
        #         return
        # if child.expect(PROMPT):
        #     return
        pass


# 终端组
class TerminalGroup:
    # 终端列表
    terminals: [Host] = []

    def __init__(self, hosts: [Host]):
        for host in hosts:
            term = Terminal(host)
            self.terminals.append(term)

    def __del__(self):
        self.disconnect()

    def connect(self):
        for term in self.terminals:
            term.connect()

    def disconnect(self):
        for term in self.terminals:
            term.disconnect()

    # 批量执行命令
    def batchExec(self, cmd: str):
        for term in self.terminals:
            term.exec(cmd)
